'use client'
import React, { useEffect, useState } from 'react'
import Loading from '@/components/common/Loading'
import PageTitle from '@/components/admin/common/PageTitle';
import request from '@/utils/request';
import { SESSION_INFORMATION, EVENTBUS_INFROMATION_UPDATE } from '@/config/settings';
import SuperInput from '@/components/admin/common/SuperInput';
import ImageUpload from '@/components/admin/common/ImageUpload';
import message from '@/components/common/message';
import isEqual from 'lodash/isEqual';
import eventBus from '@/utils/eventBus';

export default function Contact() {
  const [loaded, setLoaded] = useState(false);
  const [originalInformation, setOriginalInformation] = useState(null);
  const [state, setState] = useState(false);
  const [editedInformation, setEditedInformation] = useState({});

  const getInformation = async () => {
    setLoaded(false);
    if (sessionStorage.getItem(SESSION_INFORMATION)) {
      const data = JSON.parse(sessionStorage.getItem(SESSION_INFORMATION));
      setOriginalInformation(data);
      setEditedInformation(data);
    } else {
      const data = await request('/api/contact', { method: 'GET', credentials: 'include', });
      if (data.code !== 0) return message.error('获取信息失败！');
      setOriginalInformation(data.data);
      setEditedInformation(data.data);
      sessionStorage.setItem(SESSION_INFORMATION, JSON.stringify(data.data));
    }
    setLoaded(true);
  }

  useEffect(() => {
    getInformation();
  }, []);

  const handleChange = (key, value) => {
    setEditedInformation(prev => ({ ...prev, [key]: value }));
  }

  const handleRight = async () => {
    if (state) {
      if (!isEqual(editedInformation, originalInformation)) {
        const response = await request('/api/admin/contact', { method: 'POST', credentials: 'include', body: JSON.stringify(editedInformation) });
        if (response.code === 0) {
          message.success('保存成功！');
          setOriginalInformation(editedInformation);
          sessionStorage.setItem(SESSION_INFORMATION, JSON.stringify(editedInformation));
          eventBus.emit(EVENTBUS_INFROMATION_UPDATE);
        } else {
          message.error('保存失败！');
          return;
        }
      }
      setState(false);
    } else {
      setState(true);
    }
  }

  const handleExtra = () => {
    setEditedInformation({ ...originalInformation });
    setState(false);
  };

  const isEdited = !isEqual(editedInformation, originalInformation);
  return (
    <>
      {loaded ?
        <div>
          <PageTitle title="联系管理" buttonText={state && isEdited ? '保存' : state ? '关闭' : '编辑'} onButtonClick={handleRight} extraButtonText={state && isEdited ? '重置' : ''} onExtraButtonClick={handleExtra} />
          <div className='mb-8 rounded-smmax-w-[100%] mx-auto mt-2 flex flex-col gap-4'>
            <div className='bg-white rounded-sm px-4 py-1'>
              <ImageUpload label={'公司logo'} state={state} value={editedInformation.logo} handleChange={(value) => handleChange('logo', value)} className={'h-auto! w-60!'} />
              <ImageUpload label={'封面logo'} state={state} value={editedInformation.cover} handleChange={(value) => handleChange('cover', value)} />
              <SuperInput label={'公司名称'} state={state} value={editedInformation.name} handleChange={(value) => handleChange('name', value)} />
              <SuperInput label={'英文名称'} state={state} value={editedInformation.en_name} handleChange={(value) => handleChange('en_name', value)} />
              <SuperInput label={'公司简介'} state={state} multiline={true} value={editedInformation.description} handleChange={(value) => handleChange('description', value)} />
              <SuperInput label={'公司地址'} state={state} value={editedInformation.address} handleChange={(value) => handleChange('address', value)} />
              <SuperInput label={'联系人'} state={state} value={editedInformation.contact} handleChange={(value) => handleChange('contact', value)} />
              <SuperInput label={'微信'} state={state} value={editedInformation.wechat} handleChange={(value) => handleChange('wechat', value)} />
              <SuperInput label={'联系电话'} state={state} value={editedInformation.phone} handleChange={(value) => handleChange('phone', value)} />
              <SuperInput label={'手机号码'} state={state} value={editedInformation.mobile} handleChange={(value) => handleChange('mobile', value)} />
              <SuperInput label={'联系邮箱'} state={state} value={editedInformation.email} handleChange={(value) => handleChange('email', value)} />
            </div>
            <div className='bg-white rounded-sm px-4 py-1'>
              <SuperInput label={'公司网站'} state={state} value={editedInformation.website} handleChange={(value) => handleChange('website', value)} />
              <SuperInput label={'备案号'} state={state} value={editedInformation.icp} handleChange={(value) => handleChange('icp', value)} />
              <SuperInput label={'元标题'} state={state} value={editedInformation.meta_title} handleChange={(value) => handleChange('meta_title', value)} />
              <SuperInput label={'元描述'} state={state} multiline={true} value={editedInformation.meta_description} handleChange={(value) => handleChange('meta_description', value)} />
            </div>
          </div>
        </div>
        :
        <Loading />
      }</>
  )
}
